#ifndef UHM_DISCRETE_EXTENSION_MESH2CACHE_HXX_
#define UHM_DISCRETE_EXTENSION_MESH2CACHE_HXX_

namespace uhm {
  
  // When mesh feed connectivity in uhmfile, it is already sorted,
  // which means that connectivity order is different from uhmfile.
  // this is not a problem in real computation since there is no randomness. 
  // however, mesh-->cache does not gurantee the right connectivity.
  // matrices should fed to cache and mesh separately

  // Given mesh from a file, send connectivity to cache
  template<class M_, class C_> 
  Bool_ mesh2cache(M_ &mesh, C_ &cache, Int_ pid=0) {  
    std::vector<typename M_::Element_*> els;
    mesh.dump(els, pid);

    typename C_::_Uhm_ uhm;
    
    time_in("uhm:: mesh2cache",UHM_TIME_LEVEL_INTERNAL);
    cache.push_begin();
    for (Int_ i=0;i<els.size();++i) {
      std::vector<typename M_::Element_::Entry_> &nds = els[i]->nds();
      
      Map_< typename C_::_Id_Nd_ > factor(0), schur(nds.size());

      schur.push_begin();
      for (Int_ j=0;j<nds.size();++j) 
        schur.push(nds[j].node()->get_id());
      schur.push_end();
      
      typename C_::Entry_ in(factor, schur, uhm), *out;
      if (!cache.pull(in, &out)) {
        UHM_ERROR(cache.push(in, &out), UHM_ERROR_CACHE_PUSH);
      }
    }
    cache.push_end();
    time_out(UHM_TIME_LEVEL_INTERNAL);

    return true;
  }

}

#endif
